package com.ekuaitu.kuaitustaff.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.format.Time;
import android.util.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.Iterator;
import java.util.Map;

public class SPUtils {
    private static final String SHARED_PATH = "shared";
    private static SPUtils instance;
    private static SharedPreferences sp;
    private static SharedPreferences.Editor editor;

    public static SPUtils getInstance(Context context) {
        if (instance == null && context != null) {
            instance = new SPUtils(context);
        }
        return instance;
    }

    private SPUtils(Context context) {
        sp = context.getSharedPreferences(SHARED_PATH, Context.MODE_PRIVATE);
        editor = sp.edit();
    }

    public long getLongValue(String key) {
        if (key != null && !key.equals("")) {
            return sp.getLong(key, 0);
        }
        return 0;
    }

    public String getStringValue(String key) {
        if (key != null && !key.equals("")) {
            return sp.getString(key, null);
        }
        return null;
    }

    public int getIntValue(String key) {
        if (key != null && !key.equals("")) {
            return sp.getInt(key, 0);
        }
        return 0;
    }

    public int getIntValueByDefault(String key) {
        if (key != null && !key.equals("")) {
            return sp.getInt(key, 0);
        }
        return 0;
    }

    public boolean getBooleanValue(String key) {
        if (key != null && !key.equals("")) {
            return sp.getBoolean(key, false);
        }
        return true;
    }

    public float getFloatValue(String key) {
        if (key != null && !key.equals("")) {
            return sp.getFloat(key, 0);
        }
        return 0;
    }

    public void putStringValue(String key, String value) {
        if (key != null && !key.equals("")) {
            editor = sp.edit();
            editor.putString(key, value);
            editor.commit();
        }
    }

    public void putIntValue(String key, int value) {
        if (key != null && !key.equals("")) {
            editor = sp.edit();
            editor.putInt(key, value);
            editor.commit();
        }
    }

    public void putBooleanValue(String key, boolean value) {
        if (key != null && !key.equals("")) {
            editor = sp.edit();
            editor.putBoolean(key, value);
            editor.commit();
        }
    }

    public void putLongValue(String key, long value) {
        if (key != null && !key.equals("")) {
            editor = sp.edit();
            editor.putLong(key, value);
            editor.commit();
        }
    }

    public void putFloatValue(String key, Float value) {
        if (key != null && !key.equals("")) {
            editor = sp.edit();
            editor.putFloat(key, value);
            editor.commit();
        }
    }


    public void removeValue(String key) {
        if (key != null && !key.equals("")) {
            editor = sp.edit();
            editor.remove(key);
            editor.commit();
        }
    }
    /***
     * 写对象
     * @param key
     * @param object
     * @author caojing
     */
    public void writeObject(String key, Object object) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream out = null;
        try {
            out = new ObjectOutputStream(baos);
            out.writeObject(object);
            String objectVal = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
            editor = sp.edit();
            editor.putString(key, objectVal);
            editor.commit();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /***
     * 读对象
     *
     * @param key
     * @param clazz
     * @return
     * @author zhangg
     */
    @SuppressWarnings("unchecked")
    public <T> T readObject(String key, Class<T> clazz) {
        if (sp.contains(key)) {
            String objectVal = sp.getString(key, null);
            byte[] buffer = Base64.decode(objectVal, Base64.DEFAULT);
            ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
            ObjectInputStream ois = null;
            try {
                ois = new ObjectInputStream(bais);
                T t = (T) ois.readObject();
                return t;
            } catch (StreamCorruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (bais != null) {
                        bais.close();
                    }
                    if (ois != null) {
                        ois.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public void clearSharePreference() {
        Map<String, ?> map = sp.getAll();
        Iterator iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            String str = (String) iterator.next();
            if (!str.startsWith("$s_")) {//如果键名"$s_"开头，则退出登录时将被保留，否则清除
                editor = sp.edit();
                editor.remove(str);
                editor.commit();
            }
        }


    }

    /**
     * 判断是否是同一天
     * 是同一天返回false
     *
     * @return
     */
    public boolean isToday() {
        editor = sp.edit();
        Time t = new Time(); // or Time t=new Time("GMT+8"); 加上Time Zone资料
        t.setToNow(); // 取得系统时间。
        int year = t.year;
        int month = t.month;
        int date = t.monthDay;
        //int minute = t.minute;
        //int oldminute = sp.getInt("minute", -1);
        int oldyear = sp.getInt(SPKey.YEAR, -1);
        int oldmonth = sp.getInt(SPKey.MONTH, -1);
        int olddate = sp.getInt(SPKey.DATE, -1);

        //the first
        if (oldyear == -1 || oldmonth == -1 || olddate == -1) {
            return true;
        }
        Logger.i("TIMES", year + "年" + month + "月" + date + "日");
        if (oldyear < year) {
            Logger.i("month", month + "");
            return true;
        } else if (oldmonth < month) {
            return true;
        } else if (olddate < date) {
            return true;
        } else {
            return false;
        }
    }

    public void saveMsg() {
        editor = sp.edit();
        Time t = new Time(); // or Time t=new Time("GMT+8"); 加上Time Zone资料
        t.setToNow(); // 取得系统时间。
        int year = t.year;
        int month = t.month;
        int date = t.monthDay;
        editor.putInt(SPKey.YEAR, year);
        editor.putInt(SPKey.MONTH, month);
        editor.putInt(SPKey.DATE, date);
        editor.commit();
    }

} 